package com.kx.center.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

public class ElmUtil {

	/**
	 * 模拟饿了么get请求
	 */
	public static String elmGet(String url, String params) throws Exception {
		
		String crul = url + "?" + params;

		HttpClient httpclient = new HttpClient();
		GetMethod method = new GetMethod(crul);

		int code = httpclient.executeMethod(method);

		byte[] responseBody = null;

		if (code == HttpStatus.SC_OK) {
			Header contentEncoding = method
					.getResponseHeader("Content-Encoding");
			if (contentEncoding != null
					&& contentEncoding.getValue().toLowerCase().indexOf("gzip") > -1) {
				InputStream is = method.getResponseBodyAsStream();
				GZIPInputStream gzip = new GZIPInputStream(is);
				byte[] buf = new byte[1024];

				int num = -1;
				ByteArrayOutputStream baos = new ByteArrayOutputStream();

				while ((num = gzip.read(buf, 0, buf.length)) != -1) {
					baos.write(buf, 0, num);
				}
				responseBody = baos.toByteArray();
				baos.flush();
				baos.close();
				gzip.close();
				is.close();
			} else {
				responseBody = method.getResponseBody();
			}

			Header contentType = method.getResponseHeader("Content-Type");
			if (contentType != null) {
				String encoding = contentType.getValue().toUpperCase();

				Pattern pattern = Pattern.compile("CHARSET=([^;]*)");
				Matcher matcher = pattern.matcher(encoding);
				String charset = matcher.find() ? matcher.group(1) : null;

				if (charset != null) {
					responseBody = (new String(responseBody, charset))
							.getBytes("UTF-8");
				}
			}
		}
		String result = new String(responseBody);
		return result;
	}

	/**
	 * 模拟饿了么put请求
	 */
	public static String elmPut(String url, String params) throws Exception {

		HttpClient httpclient = new HttpClient();
		PutMethod method = new PutMethod(url);

		StringRequestEntity requestEntity = new StringRequestEntity(params,
				"application/x-www-form-urlencoded", "UTF-8");
		method.setRequestEntity(requestEntity);

		int code = httpclient.executeMethod(method);

		byte[] responseBody = null;

		if (code == HttpStatus.SC_OK) {
			Header contentEncoding = method
					.getResponseHeader("Content-Encoding");
			if (contentEncoding != null
					&& contentEncoding.getValue().toLowerCase().indexOf("gzip") > -1) {
				InputStream is = method.getResponseBodyAsStream();
				GZIPInputStream gzip = new GZIPInputStream(is);
				byte[] buf = new byte[1024];

				int num = -1;
				ByteArrayOutputStream baos = new ByteArrayOutputStream();

				while ((num = gzip.read(buf, 0, buf.length)) != -1) {
					baos.write(buf, 0, num);
				}
				responseBody = baos.toByteArray();
				baos.flush();
				baos.close();
				gzip.close();
				is.close();
			} else {
				responseBody = method.getResponseBody();
			}

			Header contentType = method.getResponseHeader("Content-Type");
			if (contentType != null) {
				String encoding = contentType.getValue().toUpperCase();

				Pattern pattern = Pattern.compile("CHARSET=([^;]*)");
				Matcher matcher = pattern.matcher(encoding);
				String charset = matcher.find() ? matcher.group(1) : null;

				if (charset != null) {
					responseBody = (new String(responseBody, charset))
							.getBytes("UTF-8");
				}
			}
		}
		String result = new String(responseBody);
		return result;
	}

	/**
	 * 模拟饿了么post请求
	 */
	public static String elmPost(String url, String data) throws HttpException,
			IOException {

		HttpClient httpclient = new HttpClient();
		PostMethod method = new PostMethod(url);

		StringRequestEntity requestEntity = new StringRequestEntity(data,
				"application/x-www-form-urlencoded", "UTF-8");
		method.setRequestEntity(requestEntity);

		int code = httpclient.executeMethod(method);

		byte[] responseBody = null;

		if (code == HttpStatus.SC_OK) {
			Header contentEncoding = method
					.getResponseHeader("Content-Encoding");
			if (contentEncoding != null
					&& contentEncoding.getValue().toLowerCase().indexOf("gzip") > -1) {
				InputStream is = method.getResponseBodyAsStream();
				GZIPInputStream gzip = new GZIPInputStream(is);
				byte[] buf = new byte[1024];

				int num = -1;
				ByteArrayOutputStream baos = new ByteArrayOutputStream();

				while ((num = gzip.read(buf, 0, buf.length)) != -1) {
					baos.write(buf, 0, num);
				}
				responseBody = baos.toByteArray();
				baos.flush();
				baos.close();
				gzip.close();
				is.close();
			} else {
				responseBody = method.getResponseBody();
			}

			Header contentType = method.getResponseHeader("Content-Type");
			if (contentType != null) {
				String encoding = contentType.getValue().toUpperCase();

				Pattern pattern = Pattern.compile("CHARSET=([^;]*)");
				Matcher matcher = pattern.matcher(encoding);
				String charset = matcher.find() ? matcher.group(1) : null;

				if (charset != null) {
					responseBody = (new String(responseBody, charset))
							.getBytes("UTF-8");
				}
			}
		}
		String result = new String(responseBody);
		return result;
	}
	
	/**
	 * 模拟饿了么delete请求
	 */
	public static String elmDelete(String url, String data) throws HttpException,
			IOException {

		HttpClient httpclient = new HttpClient();
		DeleteMethod method = new DeleteMethod(url);

		int code = httpclient.executeMethod(method);

		byte[] responseBody = null;

		if (code == HttpStatus.SC_OK) {
			Header contentEncoding = method
					.getResponseHeader("Content-Encoding");
			if (contentEncoding != null
					&& contentEncoding.getValue().toLowerCase().indexOf("gzip") > -1) {
				InputStream is = method.getResponseBodyAsStream();
				GZIPInputStream gzip = new GZIPInputStream(is);
				byte[] buf = new byte[1024];

				int num = -1;
				ByteArrayOutputStream baos = new ByteArrayOutputStream();

				while ((num = gzip.read(buf, 0, buf.length)) != -1) {
					baos.write(buf, 0, num);
				}
				responseBody = baos.toByteArray();
				baos.flush();
				baos.close();
				gzip.close();
				is.close();
			} else {
				responseBody = method.getResponseBody();
			}

			Header contentType = method.getResponseHeader("Content-Type");
			if (contentType != null) {
				String encoding = contentType.getValue().toUpperCase();

				Pattern pattern = Pattern.compile("CHARSET=([^;]*)");
				Matcher matcher = pattern.matcher(encoding);
				String charset = matcher.find() ? matcher.group(1) : null;

				if (charset != null) {
					responseBody = (new String(responseBody, charset))
							.getBytes("UTF-8");
				}
			}
		}
		String result = new String(responseBody);
		return result;
	}

	/**
	 * 拼接参数并排序
	 */
	public static String concatParams(Map<String, String> params2)
			throws UnsupportedEncodingException {
		Object[] key_arr = params2.keySet().toArray();
		Arrays.sort(key_arr);
		String str = "";

		for (Object key : key_arr) {
			String val = params2.get(key);
			key = URLEncoder.encode(key.toString(), "UTF-8");
			val = URLEncoder.encode(val, "UTF-8");
			str += "&" + key + "=" + val;
		}

		return str.replaceFirst("&", "");
	}

	private static String byte2hex(byte[] b) {
		StringBuffer buf = new StringBuffer();
		int i;

		for (int offset = 0; offset < b.length; offset++) {
			i = b[offset];
			if (i < 0)
				i += 256;
			if (i < 16)
				buf.append("0");
			buf.append(Integer.toHexString(i));
		}

		return buf.toString();
	}

	/**
	 * 获取饿了么请求sig
	 */
	public static String elmSig(String pathUrl, Map<String, String> params,
			String consumerSecret) throws NoSuchAlgorithmException,
			UnsupportedEncodingException {
		String str = concatParams(params);
		str = pathUrl + "?" + str + consumerSecret;

		MessageDigest md = MessageDigest.getInstance("SHA1");
		return byte2hex(md.digest(byte2hex(str.getBytes("UTF-8")).getBytes()));
	}

}
